package com.itheima.reggie.controller;

import com.github.pagehelper.PageInfo;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.entity.R;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishAndDishFlavorController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;


    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R insert(@RequestBody DishDto dishDto, HttpServletRequest request) {


        //生成createTime
        //生成updateTime
        dishDto.setCreateTime(LocalDateTime.now());
        dishDto.setUpdateTime(LocalDateTime.now());
        //生成createUser
        //生成updateUser
        Long isLogin = (Long) request.getSession().getAttribute("isLogin");
        dishDto.setUpdateUser(isLogin);
        dishDto.setCreateUser(isLogin);

        for (DishFlavor flavor : dishDto.getFlavors()) {
            flavor.setCreateTime(LocalDateTime.now());
            flavor.setUpdateTime(LocalDateTime.now());
            flavor.setCreateUser(isLogin);
            flavor.setUpdateUser(isLogin);
        }
        //设置code
//        dishDto.setCode("123412341234");
        //设置sort
//        dishDto.setSort(0);
        //设置is_deleted
//        dishDto.setIsDeleted(0);

        dishService.insert(dishDto);//在dishService.insert(dishDto)中将插入口味信息


        /* 保持数据库与Redis缓存一致性*/
        /*方式一:清理所有分类的缓存数据*/
//        Set keys = redisTemplate.keys("dish_*");//从Redis拿到所有以dish_开头的key
//        redisTemplate.delete(keys);

        /*方式二:只清理修改的菜品所在分类的缓存数据*/
        String key = "dish_" + dishDto.getCategoryId();
        redisTemplate.delete(key);

        return R.success("添加成功!");
    }


    @GetMapping("/page")
    public R selectBypage(int page, int pageSize, String name) {
        PageInfo<DishDto> pageInfo = dishService.selectByPage(page, pageSize, name);
        return R.success(pageInfo);//已将前端取数据时改为res.data.list
    }


    @DeleteMapping
    public R delete(@RequestParam List<String> ids) {
        for (String id : ids) {
            dishService.delete(id);
            dishFlavorService.deleteByDishId(id);
        }

        /* 保持数据库与Redis缓存一致性*/
        /*方式一:清理所有分类的缓存数据*/
        Set keys = redisTemplate.keys("dish_*");//从Redis拿到所有以dish_开头的key
        redisTemplate.delete(keys);

        /*方式二:只清理修改的菜品所在分类的缓存数据*/
//        String key = "dish_"+ dishDto.getCategoryId();
//        redisTemplate.delete(key);

        return R.success("删除成功!");
    }

    @PostMapping("/status/0")//0表示停售
    public R updateStatus_0(@RequestParam List<String> ids) {
        for (String id : ids) {
            dishService.updateStatus(id, 0);
        }
        return R.success("停售成功!");
    }

    @PostMapping("/status/1")//1表示停售
    public R updateStatus_1(@RequestParam List<String> ids) {
        for (String id : ids) {
            dishService.updateStatus(id, 1);
        }
        return R.success("启售成功!");
    }

    @GetMapping("/{id}")
    public R selectAllById(@PathVariable String id) {
        DishDto dishDto = dishService.selectAllById(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R updateById(@RequestBody DishDto dishDto, HttpServletRequest request) {
        //生成updateTime
        dishDto.setUpdateTime(LocalDateTime.now());
        //生成updateUser
        Long isLogin = (Long) request.getSession().getAttribute("isLogin");
        dishDto.setUpdateUser(isLogin);

        //修改dish表中name category_id price image description update_time update_user属性
        dishService.updateById(dishDto);

        //先根据dish_id删除dish_flavor表中的对应数据,再根据dishDto.getFlavors()插入新的数据
        //根据dish_id删除对应行数据
        dishFlavorService.deleteByDishId(dishDto.getId());
        for (DishFlavor flavor : dishDto.getFlavors()) {
            //根据dish.getFlavors()插入新的数据
            //生成createTime updateTime createUser updateUser
            flavor.setCreateTime(LocalDateTime.now());
            flavor.setUpdateTime(LocalDateTime.now());
            flavor.setCreateUser(isLogin);
            flavor.setUpdateUser(isLogin);
            //设置dish_id
            flavor.setDishId(dishDto.getId());
            dishFlavorService.insert(flavor);
        }


        /* 保持数据库与Redis缓存一致性*/
        /*方式一:清理所有分类的缓存数据*/
//        Set keys = redisTemplate.keys("dish_*");//从Redis拿到所有以dish_开头的key
//        redisTemplate.delete(keys);

        /*方式二:只清理修改的菜品所在分类的缓存数据*/
        String key = "dish_" + dishDto.getCategoryId();
        redisTemplate.delete(key);


        return R.success("修改成功");
    }


    @GetMapping("/list")
    public R selectByCategoryId(String categoryId) {
        List<Dish> dishes = null;

        //动态构造key
        String key = "dish_" + categoryId;

        //先从redis中获取缓存数据

        /*往Redis中存取时使用String类型数据即可,因为对象自动进行了序列化(对象->字节序列)和反序列化(字节序列->对象)*/

        dishes = (List<Dish>) redisTemplate.opsForValue().get(key);

        if (dishes != null) {//缓存中有数据,直接返回缓存数据,无序查询数据库
            return R.success(dishes);
        }
        //如果不存在,需要查询数据库,将查询到的菜品数据缓存到redis
        dishes = dishService.selectByCategoryId(categoryId);
        redisTemplate.opsForValue().set(key, dishes, 60, TimeUnit.MINUTES);
        return R.success(dishes);
    }

}
